package cn.yunhe.service;

import cn.yunhe.dao.IUserDao;
import cn.yunhe.entity.User;
import cn.yunhe.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

public class UserService {

    SqlSession sqlSession = null;
    IUserDao userDao = null;


    /**
     * 注册用户
     * @param user
     * @return
     */
    public int regUser(User user){
        try {
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            userDao = sqlSession.getMapper(IUserDao.class);
            int result =userDao.regUser(user);
            if (result>0){
                sqlSession.commit();
                return result;
            }else {
                sqlSession.rollback();
                return result;
            }
        }finally {
            sqlSession.close();
        }

    }


    /**
     * 用户登录
     * @return
     */
    public User userLogin(User user){
        try {
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            userDao = sqlSession.getMapper(IUserDao.class);
            User u =userDao.userLogin(user);
            if (u!=null){
                return u;
            }else {
                return null;
            }
        }finally {
            sqlSession.close();
        }

    }

    /**
     * 用户是否管理员
     * @param
     * @return
     */
    public User userIsAdmin(String name){
        try {
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            userDao = sqlSession.getMapper(IUserDao.class);
            return userDao.userIsAdmin(name);
        }finally {
            sqlSession.close();
        }
    }

    /**
     * 通过用户名，查询是否存在
     * @param name
     * @return
     */
    public boolean getAllUserByName(String name){
        try {
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            userDao = sqlSession.getMapper(IUserDao.class);
            User u = userDao.getAllUserByName(name);
            if (u!=null){
                return true;
            }else {
                return false;
            }
        }finally {
            sqlSession.close();
        }
    }







}
